from venv import logger
from common.utils import LogUtil
from hypium.action.device import UiDriver
from hypium.uidriver.uicomponent import IUiComponent
from hypium.uidriver.interface.uitree import ISelector
from hypium.model import Rect

logger = LogUtil.get_logger(__name__)

class DeviceContext:
    def __init__(self, sn: str):
        self.name = sn
        self.sn = sn
        self.board = None
        self.product = None
        self.platform = None
        self.version = None
        self.domain = None
        self.server = None
        self.address = None
        self.status = None
        self.ui_driver = None
        self.ui_driver = UiDriver.connect(device_sn=sn)

        self.frame_socket = None
        self.uitree_socket = None
        self.perf_socket = None

    def __del__(self):
        self.destroy()

    def destroy(self):
        logger.debug(f"销毁DeviceContext: {self.sn}")
        if self.ui_driver is not None:
            self.ui_driver.close()
        self.ui_driver = None

    def get_device_info(self):
        return {
            'name': self.name,
            'sn': self.sn,
            'board': self.board,
            'product': self.product,
            'platform': self.platform,
            'version': self.version,
            'domain': self.domain,
            'server': self.server,
            'address': self.address,
            'status': self.status,
        }
    
    def capture_screen(self, filename: str):
        return self.ui_driver.capture_screen(save_path=filename)
    
    def select_component(self, x: float, y: float):
        """根据比例坐标选择控件并返回控件截图路径"""
        try:
            # 获取屏幕尺寸
            screen_info = self.ui_driver.get_display_size()
            screen_width = screen_info.get('width', 1080)
            screen_height = screen_info.get('height', 1920)
            
            # 将比例坐标转换为绝对坐标
            abs_x = int(x * screen_width)
            abs_y = int(y * screen_height)
            
            logger.debug(f"选择控件坐标: 比例({x:.3f}, {y:.3f}) -> 绝对({abs_x}, {abs_y})")
            
            # 根据坐标查找控件
            component = self.ui_driver.find_component_by_position(abs_x, abs_y)
            if component is None:
                logger.warning(f"在坐标({abs_x}, {abs_y})处未找到控件")
                return None
            
            # 获取控件的边界信息
            bounds = component.get_bounds()
            logger.debug(f"找到控件，边界: {bounds}")
            
            # 生成控件截图文件名
            import time
            timestamp = int(time.time() * 1000)
            component_filename = f"component_{timestamp}.png"
            
            # 确保资源目录存在
            import os
            from common.config import WORK_PATH
            resource_dir = os.path.join(WORK_PATH, 'resources', self.sn)
            os.makedirs(resource_dir, exist_ok=True)
            
            component_filepath = os.path.join(resource_dir, component_filename)
            
            # 截取控件图片
            component_image_path = component.capture_screenshot(save_path=component_filepath)
            
            logger.debug(f"控件截图保存至: {component_image_path}")
            return component_image_path
            
        except Exception as e:
            logger.error(f"选择控件失败: {e}")
            return None